package com.zt.dev.standardManage.utils;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;

public class WordExport {

    /**
     * bytes
     * @param fileName
     * @param templateName
     * @param allMap
     * @param response
     * @param request
     */
    public void wordUlit(String fileName, String templateName, Map<String, Object> allMap, HttpServletResponse response, HttpServletRequest request) throws IOException {
        File file = FreeMarkerUtil.createWord(allMap, templateName, fileName); //创建word

        //浏览器下载文件
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            long fileLength = file.length();
            response.setContentType("application/msword");
            response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"),"ISO8859-1"));
            response.setHeader("Content-Length", String.valueOf(fileLength));
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] bytes = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(bytes, 0, bytes.length))) {
                bos.write(bytes, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
            if (fileName != null) {
                File file1 = new File(fileName);
                if (file1.exists()) {
                    file1.delete();
                }
            }
           //delFileWord(fileName);
        }
    }
    /**
     * 删除零时生成的文件
     */
    public static void delFileWord( String fileName){
        File file =new File(fileName);
        //File file1 =new File(filePath);
        file.delete();
        //file1.delete();
    }
}
